package mvc.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ResourceBundle;

/**
 * Used to create the temporary directory that stores the images used by the
 * application.
 * 
 * @author Joel
 * 
 */
public class FileUtilitys {

	private static ResourceBundle messages;

	/**
	 * Copies a file
	 * 
	 * @param sourceFile
	 *            File to copy
	 * @param destFile
	 *            Destination file to copy to
	 * @throws IOException
	 */
	public static void copyFile(File sourceFile, File destFile)
			throws IOException {
		FileChannel destination;

		if (!destFile.exists() && destFile.createNewFile()) {

			FileChannel source = null;
			destination = null;
			source = new FileInputStream(sourceFile).getChannel();
			destination = new FileOutputStream(destFile).getChannel();
			destination.transferFrom(source, 0, source.size());

			if (source != null) {
				source.close();
			}
			if (destination != null) {
				destination.close();
			}

		}
	}

	/**
	 * Deletes all files and then deletes the temporary directory.
	 * 
	 * @param path
	 *            Path to the directory.
	 */
	public static boolean removeFileDirectory(String path) {

		File directoryPath = new File(path);
		deleteDirectory(directoryPath);
		return directoryPath.delete();
	}

	// Using a recursive deletemethod found on
	// http://www.rgagnon.com/javadetails/java-0483.html
	private static void deleteDirectory(File path) {
		messages = MPResourceBundle.getResourceBundle();
		if (path.exists()) {
			File[] files = path.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					deleteDirectory(files[i]);
				} else {
					if (!files[i].delete()) {
						System.out.println(files[i].getAbsolutePath()
								+ messages.getString("couldnotbedeleted")); //$NON-NLS-1$
					}
				}
			}
		}

	}

}
